import { ProTable } from "@ant-design/pro-components";
import {
  Button,
  Modal,
  Input,
  Form,
  Checkbox,
  DatePicker,
  Space,
  Popconfirm,
  message,
  notification,
} from "antd";
import dayjs from "dayjs";
import type { GetProps } from "antd";
import { connect, history } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useEffect, useRef, useState } from "react";
import { ExclamationCircleOutlined, PlusOutlined } from "@ant-design/icons";
import Https from "@/utils/Https";
const { RangePicker } = DatePicker;

const { TextArea } = Input;
const Page = (props) => {
  const { dispatch, venueArr } = props;
  const [open, setOpen] = useState(false);
  const [row, setRow] = useState(null);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const actionRef = useRef();
  // useEffect(() => {
  //   dispatch({
  //     type: `${namespace}/pageInit`,
  //   });
  // }, []);
  type RangePickerProps = GetProps<typeof DatePicker.RangePicker>;
  const [api, contextHolder] = notification.useNotification();
  const editInfo = (params) => {
    setRow(params);
    const { startTime, endTime, venueId, id, remark, venueName } = params;
    form.setFieldsValue({
      id,
      remark,
      venueIds: venueId,
      venueName,
      rangeTime: [dayjs(startTime), dayjs(endTime)],
    });
    setOpen(true);
  };
  const deleteItem = (params) => {
    dispatch({
      type: `${namespace}/deleteItem`,
      params,
      callback: () => {
        actionRef.current?.reload();
      },
    });
  };
  const disabledDate: RangePickerProps["disabledDate"] = (current) => {
    return current && current < dayjs().subtract(1, "days");
  };
  const openNotification = (msg, type) => {
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        size="small"
        onClick={() => {
          api.destroy();
          if (type == 1) {
            history.push("/course/personal");
          } else if (type == 2) {
            history.push("/course/schedule");
          }
        }}
      >
        立即处理
      </Button>
    );
    api.open({
      message: (
        <div>
          <ExclamationCircleOutlined
            style={{ color: "red", marginRight: "8px", fontSize: "20px" }}
          />
          保存失败提示
        </div>
      ),
      description: msg,
      showProgress: true,
      pauseOnHover: true,
      duration: 3,
      key,
      btn,
    });
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    render: (id, record) => {
      return (
        <Space>
          <Button type="link" onClick={() => editInfo(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除"
            onConfirm={() => deleteItem({ id: record.id })}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      );
    },
  };

  const submitForm = async () => {
    const res = await form.validateFields();
    let { id, venueIds, remark, rangeTime } = res;
    let params = {
      id,
      //venueIds: Array.isArray(venueIds) ? venueIds.join(",") : venueIds,
      remark,
      startTime: dayjs(rangeTime[0]).format("YYYY-MM-DD 00:00:00"),
      endTime: dayjs(rangeTime[1]).format("YYYY-MM-DD 00:00:00"),
    };
    let url = params.id
      ? "/holiday/updateSingleHoliday"
      : "/holiday/venueHolidayConfig";
    setLoading(true);
    let result: any = await Https.post(url, params, true);
    setLoading(false);
    if (result.code == 200) {
      message.success("操作成功");
      setOpen(false);
      actionRef.current && actionRef.current?.reload();
    } else if (result.code == 5122) {
      openNotification(result.msg, 1);
      //私教课
    } else if (result.code == 5123) {
      openNotification(result.msg, 2);
      //团课
    } else {
      message.error(result.msg);
    }
  };

  return (
    <div>
      <ProTable
        actionRef={actionRef}
        toolBarRender={() => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setRow(null);
              form.resetFields();
              setOpen(true);
            }}
          >
            新增场馆放假
          </Button>,
        ]}
        request={async (params) => {
          return await dispatch({
            type: `${namespace}/queryTable`,
            params,
          });
        }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({ operate })}
      />
      <Modal
        open={open}
        title="场馆放假"
        forceRender
        width="40%"
        onCancel={() => setOpen(false)}
        onOk={() => {
          submitForm();
        }}
        confirmLoading={loading}
      >
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 16 }}>
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          {/* {row && (
            <>
              <Form.Item label="所属场馆" name="venueIds" hidden>
                <Input />
              </Form.Item>
              <Form.Item label="所属场馆" name="venueName" required={true}>
                <span>{form.getFieldValue("venueName")}</span>
              </Form.Item>
            </>
          )}
          {!row && (
            <Form.Item
              label="所属场馆"
              name="venueIds"
              rules={[{ required: true, message: "请选择所属场馆" }]}
            >
              <Checkbox.Group>
                {venueArr.map((v) => (
                  <Checkbox value={v.id}>{v.venueName}</Checkbox>
                ))}
              </Checkbox.Group>
            </Form.Item>
          )} */}
          <Form.Item
            label="放假时间"
            name="rangeTime"
            rules={[{ required: true, message: "请选择放假时间" }]}
          >
            <RangePicker disabledDate={disabledDate} format="YYYY-MM-DD" />
          </Form.Item>

          <Form.Item label="备注" name="remark">
            <TextArea
              showCount
              maxLength={300}
              rows={4}
              placeholder="请输入备注"
            />
          </Form.Item>
        </Form>
      </Modal>
      {contextHolder}
    </div>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(Page);
